package com.softer.wxzj.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.softer.wxzj.common.entity.CommonResult;
import com.softer.wxzj.common.entity.Page;
import com.softer.wxzj.common.enums.MessageEnum;
import com.softer.wxzj.common.enums.NumStrEnum;
import com.softer.wxzj.common.enums.NumberEnum;
import com.softer.wxzj.common.enums.ShiroResultEnum;
import com.softer.wxzj.common.error.CourseException;
import com.softer.wxzj.common.flow.enums.FlowStateEnum;
import com.softer.wxzj.common.flow.enums.FlowTypeEnum;
import com.softer.wxzj.common.flow.util.FlowAddAuditUtil;
import com.softer.wxzj.common.flow.util.FlowAuditUtil;
import com.softer.wxzj.common.flow.util.Result;
import com.softer.wxzj.common.util.OperUtil;
import com.softer.wxzj.common.util.ShiroUserUtil;
import com.softer.wxzj.entity.*;
import com.softer.wxzj.mapper.BaseHouseInfoMapper;
import com.softer.wxzj.mapper.DepReqListInfoMapper;
import com.softer.wxzj.mapper.DepositAuditMapper;
import com.softer.wxzj.mapper.DepositContinuationMapper;
import com.softer.wxzj.service.DepositAuditService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author Gong Zhiyang
 * @date 2019/6/26
 */
@Service
public class DepositAuditServiceImpl implements DepositAuditService {
    @Autowired
    private FlowAddAuditUtil flowAddAuditUtil;
    @Autowired
    private DepositAuditMapper depositAuditMapper;
    @Autowired
    private FlowAuditUtil flowUtil;
    @Autowired
    private Result result;
    @Autowired
    private BaseHouseInfoMapper baseHouseInfoMapper;
    @Autowired
    private DepReqListInfoMapper depReqListInfoMapper;
    @Autowired
    private FileServiceImpl fileService;
    @Autowired
    private DepositContinuationMapper depositContinuationMapper;

    /**
     * 交存审核
     *
     * @param list    审核ID
     * @param opinion 审批意见
     * @param mark    审批通过 audit_pass
     *                审批否决 audit_veto
     *                审批退回 audit_back
     * @return 操作结果
     */
    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
    public CommonResult audit(List<String> list, String opinion, String mark) {
        for (String businessId : list) {
            //返回审批状态
            String auditState = flowAddAuditUtil.audit(businessId, opinion, mark, null);
            if (StringUtils.isBlank(auditState)) {
                throw new CourseException(ShiroResultEnum.FAIL.getCode(), MessageEnum.FAIL.getMsg());
            }
            if (!FlowStateEnum.IN_AUDIT.getState().equals(auditState)) {
                DepReqListInfo depReqListInfo = depReqListInfoMapper.getInfo(businessId);
                //修改dep_req_list表的状态
                int num = 0;
                if (FlowStateEnum.PASS.getState().equals(auditState)) {
                    num = depositAuditMapper.updateState(businessId, auditState, ShiroUserUtil.getUserName());
                    if (num == NumberEnum.ZERO.getNum()) {
                        throw new CourseException(ShiroResultEnum.FAIL.getCode(), MessageEnum.FAIL.getMsg());
                    }
                } else {
                    num = baseHouseInfoMapper.changeFlowInProgress(NumStrEnum.ZERO.getNum(), depReqListInfo.getHouseId());
                    if (num == NumberEnum.ZERO.getNum()) {
                        throw new CourseException(ShiroResultEnum.FAIL.getCode(), MessageEnum.FAIL.getMsg());
                    }
                    num = depositAuditMapper.updateState(businessId, auditState, ShiroUserUtil.getUserName());
                    if (num == NumberEnum.ZERO.getNum()) {
                        throw new CourseException(ShiroResultEnum.FAIL.getCode(), MessageEnum.FAIL.getMsg());
                    }
                }
            }
        }
        return CommonResult.ResponseResult(NumberEnum.ONE.getNum());
    }

    /**
     * 精确查询/模糊查询 待审核列表
     *
     * @param page           分页信息
     * @param baseRegionInfo 精确查询实体
     * @param arcType        图档类型（逗号分隔）
     * @return 待审核列表
     */
    @Override
    public PageInfo<BaseRegionInfo> getAuditList(Page page, BaseRegionInfo baseRegionInfo, String arcType) {
        //查询登陆账号管理下待审核业务ID和管理区域
        Map<String, String> map = flowUtil.getBussIdAndZoneCodeByOperNo(FlowTypeEnum.DEPOSIT.getType());
        List<BaseRegionInfo> list = new ArrayList<>();
        if (null != map) {
            if (StringUtils.isBlank(baseRegionInfo.getFuzzyParam())) {
                //精确查询
                result.selectParm(map, baseRegionInfo);
                PageHelper.startPage(page.getPageNum(), page.getPageSize());
                list = depositAuditMapper.getAuditList(baseRegionInfo);
            } else {
                //模糊查询
                map.put("fuzzy", baseRegionInfo.getFuzzyParam());
                PageHelper.startPage(page.getPageNum(), page.getPageSize());
                list = depositAuditMapper.fuzzySearch(map);
            }
        }
        for (BaseRegionInfo b : list) {
            // 查询图档信息
            List<FileVO> fileVOList = fileService.getFileVOList(b.getBusinessId(), arcType);
            b.setFileTypeList(fileVOList);
        }
        PageInfo<BaseRegionInfo> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    /**
     * 查询单个小区交存审核列表
     *
     * @param id 小区ID
     * @return 审核列表
     */
    @Override
    public List<DepositAudit> getAuditListByRegionId(String id) {
        //查询登陆账号管理下待审核业务ID和管理区域
        Map<String, String> map = flowUtil.getBussIdAndZoneCodeByOperNo(FlowTypeEnum.DEPOSIT.getType());
        List<DepositAudit> list = new ArrayList<>();
        if (null != map) {
            map.put("regionId", id);
            list = depositAuditMapper.getAuditListByRegionId(map);
        }

        return list;
    }

    /**
     * 交存全部审核
     *
     * @param id      小区ID
     * @param opinion 审批意见
     * @param mark    审批通过 audit_pass
     *                审批否决 audit_veto
     *                审批退回 audit_back
     * @return 操作结果
     */
    @Override
    public CommonResult auditAll(String id, String opinion, String mark) {
        //查询登陆账号管理下待审核业务ID和管理区域
        Map<String, String> map = flowUtil.getBussIdAndZoneCodeByOperNo(FlowTypeEnum.DEPOSIT.getType());
        List<DepositAudit> list = new ArrayList<>();
        if (null != map) {
            map.put("regionId", id);
            list = depositAuditMapper.getAuditListByRegionId(map);
        }
        if (list.size() > NumberEnum.ZERO.getNum()) {
            List<String> collect = list.stream().map(DepositAudit::getId).collect(Collectors.toList());
            return audit(collect, opinion, mark);
        }
        return CommonResult.ResponseResult(NumberEnum.ZERO.getNum());
    }

    /**
     * 交存审核查询列表
     *
     * @param page         分页实体
     *                     pageNum 页码
     *                     pageSize 每页条数
     * @param depositAudit 查询实体
     *                     regionName 小区名称
     *                     regionNo 小区编码
     *                     houseSite房屋地址
     *                     flowState 审核状态
     *                     creater 申请人
     * @param fuzzy        模糊查询字段
     * @return 审核查询列表
     */
    @Override
    public PageInfo<DepositAudit> getAuditSearchList(Page page, DepositAudit depositAudit, String fuzzy) {
        List<DepositAudit> list;
        String zoneCode = OperUtil.zoneCodeUtil.getZoneCode();
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        if (StringUtils.isBlank(fuzzy)) {
            //精确查询
            depositAudit.setZoneCode(zoneCode);
            list = depositAuditMapper.getAuditSearchList(depositAudit);
        } else {
            //模糊查询
            list = depositAuditMapper.fuzzyAuditSearchList(fuzzy, zoneCode);
        }
        PageInfo<DepositAudit> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }
}
